#include<iostream>
#include<string>
#include<mysql/mysql.h>
using namespace std;

const std::string host="127.0.0.1";
const std::string user="yzy_test";//登录用户
const std::string password = "y123456789";//登陆密码
const std::string db = "study";//数据库名
const unsigned int port = 8080;//端口

int main()
{
    cout<< mysql_get_client_info() <<endl;

    //0. 创建mysql句柄
    MYSQL* my = mysql_init(nullptr);
    //1. 链接数据库
    if(mysql_real_connect(my,host.c_str(),user.c_str(), password.c_str(),db.c_str(),port, nullptr, 0) == nullptr)
    {
        fprintf(stderr, "Failed to connect to database: Error: %s\n",
        mysql_error(my));
        return 1;
    }
    //1.1: 需要设置链接的编码格式
    mysql_set_character_set(my, "utf8");
    std::cout << "connect success" << std::endl;
    //2. 访问 数据库.test id, name
    //这三个是最简单的，只要sql执行完毕，就可以了
    // std::string sql = "insert into test values (4, \'猪八戒\')";
    // std::string sql = "delete from test where id=3";
    // std::string sql = "update test set name=\'唐僧\' where id=2";

    //2.1 select sql执行完，只是第一步，还需要对数据进一步解析！
    std::string sql = "select name from test where id = 4";
    int code = mysql_query(my, sql.c_str());//语句调用
    if(code != 0)
    {
        std::cout << "execute: " << sql << " failed" << std::endl;
        return 2;
    }
    std::cout << "execute: " << sql << " success" << std::endl;
    //2.2 解析数据 -- 获取行号和列号
    MYSQL_RES *result = mysql_store_result(my);
    int rows = mysql_num_rows(result);
    int cols = mysql_num_fields(result);
    std::cout << "行数: " << rows << ", 列数: " << cols << std::endl;

    //2.3 解析数据 -- 获取表中列名 -- 一般不用，仅仅是为了测试代码的完整性
    MYSQL_FIELD *fields = mysql_fetch_fields(result);
    for(int i = 0; i < cols; i++)
    {
        std::cout << fields[i].name << "\t";
    }
    std::cout << std::endl;

    //2.4 解析数据 -- 获取表中的数据 -- 重要
    for(int i = 0; i < rows; i++)
    {
        MYSQL_ROW line = mysql_fetch_row(result); //获取完整的一行记录[可能包含了多列]
        for(int j = 0; j < cols; j++)
        {
            std::cout << line[j] << "\t"; //将记录内部的多列字符串依次打印！
        }
        std::cout << std::endl;
    }

    //3. 关闭数据库
    free(result);
    mysql_close(my);
    return 0;
}